%!TEX program = xelatex
% Encoding: UTF8
% SEIKA 2016 ｜ seika@live.ca

% Chapter 1
% Section 1.3 Introduction

\section{Basic Usage   ||   使用基础} \label{basic_usage}

Ⓔ \textcolor{etc}{To use TensorFlow you need to understand how TensorFlow:}

\begin{itemize}
\item \textcolor{etc}{Represents computations as \emph{graphs}.}
\item \textcolor{etc}{Executes graphs in the context of \lstinline{Sessions}.}
\item \textcolor{etc}{Represents data as \emph{tensors}.}
\item \textcolor{etc}{Maintains state with \lstinline{Variables}.}
\item \textcolor{etc}{Uses feeds and fetches to get data into and out of arbitrary operations.}
\end{itemize}

Ⓒ 使用TensorFlow之前你需要了解关于TensorFlow的以下基础知识:

\begin{itemize}
\item 使用\emph{图}(\emph{graphs})来表示计算.\index{graph}
\item 在\emph{会话}(\lstinline{Session})中执行图.\index{session}
\item 使用\emph{张量}(\emph{tensors})来代表数据.\index{tensor}
\item 通过\emph{变量}(\lstinline{Variables})维护状态.\index{variable}
\item 使用\emph{供给}(\lstinline{feeds})和\emph{取回}(\lstinline{fetches})将数据传入或传出任何操作.
\end{itemize}

%
%%
\subsection{Overview  |  总览}

Ⓔ \textcolor{etc}{TensorFlow is a programming system in which you represent computations as graphs. Nodes in the graph are called ops (short for operations). An op takes zero or more \emph{Tensors}, performs some computation, and produces zero or more \emph{Tensors}. A Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of floating point numbers with dimensions \lstinline{[batch, height, width, channels]}.}

Ⓒ TensorFlow 是一个以\emph{图}(\emph{graphs})来表示计算的编程系统,图中的节点被称之为 op~(operation的缩写). 一个 op 获得零或多个\emph{张量}(\emph{tensors})执行计算,产生零或多个\emph{张量}。\emph{张量} 是一个按类型划分的多维数组。例如, 你可以将一小组图像集表示为一个四维浮点数数组,这四个维度分别是\lstinline{[batch, height, width, channels]}。

Ⓔ \textcolor{etc}{A TensorFlow graph is a description of computations. To compute anything, a graph must be launched in a \lstinline{Session}. A Session places the graph ops onto \lstinline{Devices}, such as CPUs or GPUs, and provides methods to execute them. These methods return tensors produced by ops as \href{http://www.numpy.org/}{numpy} ndarray objects in Python, and as \lstinline{tensorflow::Tensor} instances in C and C++.}

Ⓒ TensorFlow的图是一种对计算的抽象描述。在计算开始前, 图必须在 \emph{会话}(\lstinline{Session()}) 中被启动.\emph{会话}将图的op分发到如 CPU 或 GPU 之类的 \emph{设备}(\lstinline{Devices()}) 上, 同时提供执行 op 的方法。这些方法执行后, 将产生的\emph{张量}(\emph{tensor})返回。在 Python 语言中, 将返回\href{http://www.numpy.org}{numpy}的\lstinline{ndarray} 对象; 在 C 和 C++ 语言中, 将返回\lstinline{tensorflow::Tensor}实例。


%
%%
%✠ \subsection{The computation graph}
\subsection {The computation graph  |  计算图} \label{computation_graph}

Ⓔ \textcolor{etc}{TensorFlow programs are usually structured into a \emph{construction phase}, that assembles a graph, and an \emph{execution phase} that uses a session to execute ops in the graph.}

Ⓒ 通常，TensorFlow编程可按两个阶段组织起来:\emph{构建阶段}和\emph{执行阶段};前者用于组织\emph{计算图}，而后者利用session中执行\emph{计算图}中的op操作。

Ⓔ \textcolor{etc}{For example, it is common to create a graph to represent and train a neural network in the construction phase, and then repeatedly execute a set of training ops in the graph in the execution phase.}

Ⓒ 例如,在构建阶段创建一个图来表示和训练神经网络，然后在执行阶段反复执行一组op来实现图中的训练。

Ⓔ \textcolor{etc}{TensorFlow can be used from C, C++, and Python programs. It is presently much easier to use the Python library to assemble graphs, as it provides a large set of helper functions not available in the C and C++ libraries.}

Ⓒ TensorFlow 支持 C、 C++、 Python 编程语言。 目前, TensorFlow 的 Python 库更加易用,它提供了大量的辅助函数来简化构建图的工作, 而这些函数在 C 和 C++ 库中尚不被支持。

Ⓔ \textcolor{etc}{The session libraries have equivalent functionalities for the three languages.}

Ⓒ 这三种语言的会话库 (session libraries) 是一致的.

%%%
% \subsubsection {Building the graph}
\subsubsection {Building the graph  |  构建计算图}

Ⓔ \textcolor{etc}{To build a graph start with ops that do not need any input (source ops), such as Constant, and pass their output to other ops that do computation.}

Ⓒ 刚开始基于op建立图的时候一般不需要任何的输入源(source op)，例如输入常量(\lstinline{Constance})，再将它们传递给其它 op 执行运算。

Ⓔ \textcolor{etc}{The ops constructors in the Python library return objects that stand for the output of the constructed ops. You can pass these to other ops constructors to use as inputs.}

Ⓒ Python库中的op构造函数返回代表已被组织好的op作为输出对象，这些对象可以传递给其它
op构造函数作为输入。

Ⓔ \textcolor{etc}{The TensorFlow Python library has a default graph to which ops constructors add nodes. The default graph is sufficient for many applications. See the \hyperref[class-tf.graph]{Graph class} documentation for how to explicitly manage multiple graphs.}

Ⓒ TensorFlow Python 库有一个可被 op构造函数加入计算结点的默认图 (default graph)。 对大多数应用来说，这个默认图已经足够用了。阅读 \hyperref[class-tf.graph]{Graph 类}文档来了解如何明晰的管理多个图.

\begin{lstlisting}
import tensorflow as tf

# Create a Constant op that produces a 1x2 matrix.  The op is
# added as a node to the default graph.
#
# The value returned by the constructor represents the output
# of the Constant op.
matrix1 = tf.constant([[3., 3.]])

# Create another Constant that produces a 2x1 matrix.
matrix2 = tf.constant([[2.],[2.]])

# Create a Matmul op that takes 'matrix1' and 'matrix2' as inputs.
# The returned value, 'product', represents the result of the matrix
# multiplication.
product = tf.matmul(matrix1, matrix2)
\end{lstlisting}

Ⓔ \textcolor{etc}{The default graph now has three nodes: two constant() ops and one matmul() op. To actually multiply the matrices, and get the result of the multiplication, you must launch the graph in a session.}

Ⓒ 默认图现在拥有三个节点，两个\lstinline{constant()} op，一个\lstinline{matmul()} op. 为了真正进行矩阵乘法运算，得到乘法结果, 你必须在一个会话(session)中载入启动这个图。


%%%
\subsubsection {Launching the graph in a session  |  在会话中载入图} \label{launching_graph}

Ⓔ \textcolor{etc}{Launching follows construction. To launch a graph, create a Session object. Without arguments the session constructor launches the default graph.}

Ⓔ \textcolor{etc}{See the \hyperref[class-tf.session]{Session class} for the complete session API.}

Ⓒ 构建过程完成后就可运行执行过程。为了载入之前所构建的图，必须先创建一个\emph{会话}对象(\lstinline{Session} object)。会话构建器在未指明参数时会载入默认的图。

Ⓒ 完整的会话API资料，请参见\hyperref[class-tf.session]{\emph{会话类}(Session object)}。

\begin{lstlisting}
# Launch the default graph.
sess = tf.Session()

# To run the matmul op we call the session 'run()' method, passing 'product'
# which represents the output of the matmul op.  This indicates to the call
# that we want to get the output of the matmul op back.
#
# All inputs needed by the op are run automatically by the session.  They
# typically are run in parallel.
#
# The call 'run(product)' thus causes the execution of threes ops in the
# graph: the two constants and matmul.
#
# The output of the op is returned in 'result' as a numpy `ndarray` object.
result = sess.run(product)
print(result)
# ==> [[ 12.]]

# Close the Session when we're done.
sess.close()
\end{lstlisting}

Ⓔ \textcolor{etc}{Sessions should be closed to release resources. You can also enter a Session with a "with" block. The Session closes automatically at the end of the with block.}

Ⓒ 会话在完成后必须关闭以释放资源。你也可以使用\lstinline{"with"}句块开始一个会话，该会话将在\lstinline{"with"}句块结束时自动关闭。

\begin{lstlisting}
with tf.Session() as sess:
  result = sess.run([product])
  print(result)
\end{lstlisting}

Ⓔ \textcolor{etc}{The TensorFlow implementation translates the graph definition into executable operations distributed across available compute resources, such as the CPU or one of your computer's GPU cards. In general you do not have to specify CPUs or GPUs explicitly. TensorFlow uses your first GPU, if you have one, for as many operations as possible.}

Ⓒ TensorFlow 事实上通过一个“翻译”过程，将定义的图转化为不同的可用计算资源间实现分布计算的操作，如CPU或是显卡GPU。通常不需要用户指定具体使用的CPU或GPU，TensorFlow 能自动检测并尽可能的充分利用找到的第一个 GPU 进行运算。

Ⓔ \textcolor{etc}{If you have more than one GPU available on your machine, to use a GPU beyond the first you must assign ops to it explicitly. Use with...Device statements to specify which CPU or GPU to use for operations:}

Ⓒ 如果你的设备上有不止一个GPU，你需要明确指定op操作到不同的运算设备以调用它们。使用\lstinline{with...Device}语句明确指定哪个CPU或GPU将被调用:

\begin{lstlisting}
with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)
    ...
\end{lstlisting}

Ⓔ \textcolor{etc}{Devices are specified with strings. The currently supported devices are:}\\
Ⓔ \textcolor{etc}{\lstinline{"/cpu:0"}: The CPU of your machine.}\\
Ⓔ \textcolor{etc}{\lstinline{"/gpu:0"}: The GPU of your machine, if you have one.}\\
Ⓔ \textcolor{etc}{\lstinline{"/gpu:1"}: The second GPU of your machine, etc.}

Ⓔ \textcolor{etc}{See Using GPUs for more information about GPUs and TensorFlow.}

Ⓒ 使用字符串指定设备，目前支持的设备包括:\\
Ⓒ \lstinline{"/cpu:0"}：计算机的CPU；\\
Ⓒ \lstinline{"/gpu:0"}：计算机的第一个GPU，如果可用；\\
Ⓒ \lstinline{"/gpu:1"}：计算机的第二个GPU，以此类推。

Ⓒ 关于使用GPU的更多信息，请参阅\textbf{GPU使用}。

%
%%
\subsection{Interactive Usage  |  交互式使用}

Ⓔ \textcolor{etc}{The Python examples in the documentation launch the graph with a \hyperref[class-tf.session]{\lstinline{Session}} and use the \hyperref[tf.session.run]{\lstinline{Session.run()}} method to execute operations.}

Ⓔ \textcolor{etc}{For ease of use in interactive Python environments, such as \href{http://ipython.org/}{\lstinline{IPython}} you can instead use the \hyperref[class-tf.interactivesession]{\lstinline{InteractiveSession}} class, and the \hyperref[tf.tensor.eval]{\lstinline{Tensor.eval()}} and \hyperref[tf.operation.run]{\lstinline{Operation.run()}} methods. This avoids having to keep a variable holding the session.}

Ⓒ 文档中的 Python 示例使用一个会话 \hyperref[class-tf.session]{\lstinline{Session}} 来启动图, 并调用 \hyperref[tf.session.run]{\lstinline{Session.run()}} 方法执行操作。

Ⓒ 考虑到如\href{http://ipython.org}{IPython}这样的交互式Python环境的易用, 可以使用\hyperref[class-tf.interactivesession]{\lstinline{InteractiveSession}} 代替\lstinline{Session}类, 使用 \hyperref[tf.tensor.eval]{\lstinline{Tensor.eval()}}和 \hyperref[tf.operation.run]{\lstinline{Operation.run()}} 方法代替 \lstinline{Session.run()}. 这样可以避免使用一个变量来持有会话.

\begin{lstlisting}
# Enter an interactive TensorFlow Session.
import tensorflow as tf
sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()

# Add an op to subtract 'a' from 'x'.  Run it and print the result
sub = tf.subtract(x, a)
print(sub.eval())
# ==> [-2. -1.]

# Close the Session when we're done.
sess.close()
\end{lstlisting}

%
%%

\subsection{Tensors  |  张量}
Ⓔ \textcolor{etc}{TensorFlow programs use a tensor data structure to represent all data -- only tensors are passed between operations in the computation graph. You can think of a TensorFlow tensor as an n-dimensional array or list. A tensor has a static type, a rank, and a shape. To learn more about how TensorFlow handles these concepts, see the \href{https://www.tensorflow.org/versions/master/resources/dims_types.html#tensor-ranks-shapes-and-types}{Rank, Shape, and Type} reference.}

Ⓒ TensorFlow 程序使用 tensor 数据结构来代表所有的数据, 计算图中, 操作间传递的数据都是 tensor. 你可以把 TensorFlow 的张量看作是一个 n 维的数组或列表. 一个 tensor 包含一个静态类型 rank, 和一个 shape. 想了解 TensorFlow 是如何处理这些概念的, 参见 Rank, Shape, 和 Type]。


%
%%
\subsection{Variables  |  变量}

Ⓔ \textcolor{etc}{Variables maintain state across executions of the graph. The following example shows a variable serving as a simple counter. See \hyperref[variables]{Variables} for more details.}

Ⓒ \emph{变量}维持了图执行过程中的状态信息。下面的例子演示了如何使用变量实现一个简单的计数器，更多细节详见\hyperref[variables]{变量}章节。

\begin{lstlisting}
# Create a Variable, that will be initialized to the scalar value 0.
# 建立一个变量，用0初始化它的值
state = tf.Variable(0, name="counter")

# Create an Op to add one to `state`.

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

# Variables must be initialized by running an `init` Op after having
# launched the graph.  We first have to add the `init` Op to the graph.
init_op = tf.global_variables_initializer()

# Launch the graph and run the ops.
with tf.Session() as sess:
  # Run the 'init' op
  sess.run(init_op)
  # Print the initial value of 'state'
  print(sess.run(state))
  # Run the op that updates 'state' and print 'state'.
  for _ in range(3):
    sess.run(update)
    print(sess.run(state))

# output:

# 0
# 1
# 2
# 3
\end{lstlisting}

Ⓔ \textcolor{etc}{The \lstinline{assign()} operation in this code is a part of the expression graph just like the \lstinline{add()} operation, so it does not actually perform the assignment until \lstinline{run()} executes the expression.}

Ⓒ 代码中\lstinline{assign()}操作是图所描绘的表达式的一部分, 正如\lstinline {add()}操作一样. 所以在调用\lstinline {run()}执行表达式之前, 它并不会真正执行赋值操作.

Ⓔ \textcolor{etc}{TYou typically represent the parameters of a statistical model as a set of Variables. For example, you would store the weights for a neural network as a tensor in a Variable. During training you update this tensor by running a training graph repeatedly.}

Ⓒ 通常会将一个统计模型中的参数表示为一组变量. 例如, 你可以将一个神经网络的权重作为某个变量存储在一个 tensor 中. 在训练过程中, 通过重复运行训练图, 更新这个 tensor.


%
%%
\subsection{Fetches  |  取回}

Ⓔ \textcolor{etc}{To fetch the outputs of operations, execute the graph with a \lstinline{run()} call on the \lstinline{Session} object and pass in the tensors to retrieve. In the previous example we fetched the single node \lstinline{state}, but you can also fetch multiple tensors:}

Ⓒ 为了取回操作的输出内容, 可以在使用 \lstinline{Session} 对象的 \lstinline{run()} 调用 执行图时, 传入一些 tensor,这些 tensor 会帮助你取回结果. 在之前的例子里, 我们只取回了单个节点\lstinline{state}, 但是你也可以取回多个tensor:

\begin{lstlisting}
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.multiply(input1, intermed)

with tf.Session() as sess:
  result = sess.run([mul, intermed])
  print(result)

# output:
# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]
\end{lstlisting}

Ⓔ \textcolor{etc}{All the ops needed to produce the values of the requested tensors are run once (not once per requested tensor).}

Ⓒ 需要获取的多个 tensor 值，在 op 的一次运行中一起获得（而不是逐个去获取 tensor）。

%
%%
\subsection{Feeds  |  供给}

Ⓔ \textcolor{etc}{The examples above introduce tensors into the computation graph by storing them in \lstinline{Constants} and \lstinline{Variables}. TensorFlow also provides a feed mechanism for patching a tensor directly into any operation in the graph.}

Ⓒ 上述示例在计算图中引入了 tensor, 以 \emph{常量} (\lstinline{Constants}) 或 \emph{变量}(\lstinline{Variables}) 的形式存储. TensorFlow 还提 \emph{供给}(\emph{feed}) 机制, 该机制可临时替代图中的任意操作中的 tensor 可以对图中任何操作提交补丁, 直接插入一个 tensor.

Ⓔ \textcolor{etc}{A feed temporarily replaces the output of an operation with a tensor value. You supply feed data as an argument to a \lstinline{run()} call. The feed is only used for the run call to which it is passed. The most common use case involves designating specific operations to be "feed" operations by using \lstinline{tf.placeholder()} to create them:}

Ⓒ feed 使用一个 tensor 值临时替换一个操作的输出结果. 你可以提供 feed 数据作为 \lstinline {run()} 调用的参数.feed 只在调用它的方法内有效, 方法结束, feed 就会消失. 最常见的用例是将某些特殊的操作指定为 "feed" 操作, 标记的方法是使用\lstinline{tf.placeholder()}为这些操作创建占位符.

\begin{lstlisting}
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

with tf.Session() as sess:
  print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))

# output:
# [array([ 14.], dtype=float32)]
\end{lstlisting}

Ⓔ \textcolor{etc}{A \lstinline{placeholder()} operation generates an error if you do not supply a feed for it. See the \hyperref[minist_tf]{MNIST fully-connected feed tutorial} (\href{https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/g3doc/tutorials/mnist/fully_connected_feed.py}{source code}) for a larger-scale example of feeds.}

Ⓒ 如果没有正确供给, \lstinline{placeholder()} 操作将会产生一个错误提示.关于feed的规模更大的案例，参见\hyperref[minist_tf]{MNIST 全连通 feed 教程}以及其\href{https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/g3doc/tutorials/mnist/fully_connected_feed.py}{源代码}。

\href{http://tensorflow.org/get_started/basic_usage.md}{原文：Basic Usage}
